<?php

class PaymentController extends FrontEndController
{
	public function actionIndex()
	{
		$this->render('index');
	}

	public function actionSuccessful()
	{
		$api = new BaoKimPayment();
                $rs = $api->verifyResponseUrl($_GET);
                $order_id = $_GET['order_id'];
                $id = Format::getFormId($order_id);
                if($rs){
                    $pay_at = date('Y-m-d H:i:s',$_GET['created_on']);
                    try {
                        if(isset($_GET['order_id'])){
                            $form = Form::model()->findByPk($id);
                            if($form){
                                $paid =   (float) $form->paid;
                                $remain = (float)$form->remain;
                                $pay = (float)$_GET['total_amount'];
                                $form->paid = $paid + $pay;
                                $form->remain = $pay > $form->remain ? 0 : $form->remain - $pay;
                                $form->save();
                            }
                        }
                    } catch (Exception $exc) {
                    }
                    try {
                        if(isset($_GET['order_id'])){
                            $order_id = $_GET['order_id'];
                            $id = Format::getFormId($order_id);
                            $payment = new Payment();
                            $payment->amount = (float)$_GET['total_amount'];
                            $payment->detail = CJSON::encode($_GET);
                            $payment->transection_id = $_GET['transaction_id'];
                            $payment->user_pay = Yii::app()->user->id;
                            $payment->pay_at = $pay_at;
                            $payment->order_id = $order_id;
                            $payment->sender_name = $_GET['customer_name'];
                            $form = Form::model()->findByPk($id);
                            if($form){
                                $payment->form_id = $id;
                            }
                            $payment->save();
                        }
                    } catch (Exception $exc) {
                    }
                }
                $form = Form::model()->findByPk($id);
                Yii::app()->user->setFlash('success', 'Bạn đã thanh toán thành công !');
                if($form){
                    $redirect_url = Format::getFormLink($id, $form->type,'update');
                }else{
                    $redirect_url = Yii::app()->getBaseUrl();
                }
                $this->redirect($redirect_url);
	}
        public function actionCancel()
	{
		$api = new BaoKimPayment();
                $rs = $api->verifyResponseUrl($_GET);
                var_dump($rs);
                var_dump($_GET);
	}

	
}